package com.allscore.batch.test.handler;

import com.allscore.batch.test.util.DateUtils;
import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
import org.springframework.stereotype.Component;

/**
 * 批处理任务事前事后处理
 */
@Component
public class CsvListener extends JobExecutionListenerSupport {

	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public void afterJob(JobExecution jobExecution) {
		
		logger.info("批量读取csv入库任务结束...统计↓↓↓↓↓↓");
		
		Collection<StepExecution> steps = jobExecution.getStepExecutions();//获取步骤结果
		for(StepExecution stepResult : steps) {
			logger.info( stepResult.getStepName() + "  -------步骤数据统计 BEGIN ----------------------------------");
			logger.info("总计输入记录数：" + stepResult.getReadCount());
			logger.info("总计输出记录数：" + stepResult.getWriteCount());
			logger.info("开始执行时间：" + DateUtils.convertJavaDateToStr(stepResult.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
			logger.info("执行结束时间：" + DateUtils.convertJavaDateToStr(stepResult.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
			logger.info("总计跳过记录数：" + stepResult.getSkipCount());
			logger.info("被ItemProcessor跳过的记录数：" + stepResult.getFilterCount());
			logger.info("输入失败跳过的记录数：" + stepResult.getReadSkipCount());
			logger.info("输出失败跳过的记录数：" + stepResult.getWriteSkipCount());
			logger.info("执行过程中失败跳过的记录数：" + stepResult.getProcessSkipCount());
			logger.info("事务成功提交次数，非记录数：" + stepResult.getCommitCount());
			logger.info("事务回滚记录数，非记录数：" + stepResult.getRollbackCount());
			logger.info("退出(异常退出或执行完成)步骤后的状态：" + stepResult.getExitStatus().getExitCode());//UNKNOWN    COMPLETED   NOOP    FAILED    STOPPED
			logger.info("步骤最终状态" + stepResult.getStatus());//STARTING   STARTED   FAILED   STOPPING   STOPPED   COMPLETED 
			logger.info( stepResult.getStepName() + "  -------步骤数据统计 END -------------------------------------");
		}
	}

	@Override
	public void beforeJob(JobExecution jobExecution) {
		logger.info("开始处理读取CSV文件，插入数据库..."+jobExecution.getExitStatus());
	}

}
